#!/usr/bin/env python3
# getuserprocs.py

from subprocess import Popen, PIPE
from re import split
from sys import stdout
import os, sys, getpass
sys.path.insert(0, r'/home/george/Projects/ISH') # Change to install path.. like /opt/something
import dialog

class Proc(object):
    ''' Data structure for a processes . The class properties are process attributes. '''
    def __init__(self, proc_info):
        self.user = proc_info[0]
        self.pid = proc_info[1]
        self.cpu = proc_info[2]
        self.mem = proc_info[3]
        self.vsz = proc_info[4]
        self.rss = proc_info[5]
        self.tty = proc_info[6]
        self.stat = proc_info[7]
        self.start = proc_info[8]
        self.time = proc_info[9]
        self.cmd = proc_info[10]

    def to_str(self):
        ''' Returns a string containing minimalistic info about the process : user, pid, and command. '''
        return '%s %s %s' % (self.user, self.pid, self.cmd)

def get_proc_list():
    ''' Retrieves a list of Proc objects representing the active processes. '''
    proc_list = []
    sub_proc = Popen(['ps', 'aux'], shell=False, stdout=PIPE)
    #Discard the first line (ps aux header)
    sub_proc.stdout.readline()
    for line in sub_proc.stdout:
        # Decode to utf-8, strict, replace, ignore are possible values.
        utfline = line.decode("utf-8", "strict")
        #The separator for splitting is 'variable number of spaces'
        proc_info = split(" *", utfline.strip())
        proc_list.append(Proc(proc_info))
    return proc_list

# Move to dialog.py eventually
def get_logfile():
    ''' Get path for log file, should probably be stored outside of user dir. '''
    home = dialog.get_userdir()
    logdir = home + "/.support"
    os.makedirs(logdir, exist_ok=True) # Create logdir if not exist.
    username = dialog.get_username()
    time = dialog.get_time()
    log_file = logdir + "/" + username + "_" + time + ".proc"
    if log_file: return log_file
    else: return None

if __name__ == "__main__":
    proc_list = get_proc_list()
    # Collect a list of processes that are owned by user
    user_name = dialog.get_username()
    user_proc_list = [ x for x in proc_list if x.user == user_name ]
    
    # Convert Proc into str a collect in a list
    usr_prcs = []   
    for proc in user_proc_list:
            usr_prcs.append(proc.to_str())
    
    # Convert the list to one big string
    user_proc_string = ('\n'.join(map(str, usr_prcs)))
    log_file = get_logfile()

    with open(log_file, 'w') as f:    
        f.write(user_proc_string)
